from flask import Flask, request, jsonify, session, send_from_directory
from flask_mysqldb import MySQL
from flask_cors import CORS
import bcrypt

app = Flask(__name__)
CORS(app)

app.config['MYSQL_USER'] = 'myuser'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'dbsclab2018'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_PORT'] = 3306
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
app.secret_key = '123456'

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username')
    password = request.json.get('password')
    cursor = mysql.connection.cursor()
    cursor.execute('SELECT password FROM users WHERE username = %s', (username,))
    user = cursor.fetchone()
    cursor.close()

    if user and bcrypt.check_password_hash(user['password'], password):
        session['CURRENT_USERNAME'] = username
        return jsonify({'success': True}), 200
    else:
        return jsonify({'success': False, 'message': 'Invalid credentials'}), 401

@app.route('/chat_history', methods=['GET'])
def get_chat_history():
    b = session.get('CURRENT_USERNAME')
    if not b:
        return jsonify({'error': 'User not logged in'}), 401

    cursor = mysql.connection.cursor()
    cursor.execute('SELECT question, answer FROM chat_history WHERE username = %s', (b,))
    chat_history = cursor.fetchall()
    cursor.close()
    return jsonify(chat_history), 200

@app.route('/')
def index():
    return send_from_directory(app.static_folder, 'search.html')

if __name__ == '__main__':
    app.run(debug=True, port=5001)